/**
 * 后台管理通用JavaScript
 * 处理侧边栏收缩、移动端适配等功能
 */

class AdminUI {
    constructor() {
        this.sidebar = document.querySelector('.sidebar');
        this.mainContent = document.querySelector('.main-content');
        this.sidebarToggle = document.querySelector('.sidebar-toggle');
        this.isMobile = window.innerWidth <= 768;
        this.isCollapsed = false;
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.setupResponsiveBehavior();
        this.loadSidebarState();
    }
    
    setupEventListeners() {
        // 侧边栏切换按钮
        if (this.sidebarToggle) {
            this.sidebarToggle.addEventListener('click', () => {
                this.toggleSidebar();
            });
        }
        
        // 窗口大小变化监听
        window.addEventListener('resize', () => {
            this.handleResize();
        });
        
        // 点击主内容区关闭移动端侧边栏
        if (this.mainContent && this.isMobile) {
            this.mainContent.addEventListener('click', () => {
                if (this.sidebar.classList.contains('show')) {
                    this.hideSidebar();
                }
            });
        }
        
        // ESC键关闭侧边栏
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.isMobile && this.sidebar.classList.contains('show')) {
                this.hideSidebar();
            }
        });
    }
    
    setupResponsiveBehavior() {
        if (this.isMobile) {
            this.setupMobileBehavior();
        } else {
            this.setupDesktopBehavior();
        }
    }
    
    setupMobileBehavior() {
        // 移动端：默认隐藏侧边栏
        this.hideSidebar();
        
        // 显示顶部导航栏
        const topNavbar = document.querySelector('.top-navbar');
        if (topNavbar) {
            topNavbar.style.display = 'flex';
        }
        
        // 显示侧边栏切换按钮
        if (this.sidebarToggle) {
            this.sidebarToggle.style.display = 'block';
        }
    }
    
    setupDesktopBehavior() {
        // 桌面端：默认显示侧边栏
        this.showSidebar();
        
        // 隐藏顶部导航栏
        const topNavbar = document.querySelector('.top-navbar');
        if (topNavbar) {
            topNavbar.style.display = 'none';
        }
        
        // 显示侧边栏切换按钮（桌面端也需要）
        if (this.sidebarToggle) {
            this.sidebarToggle.style.display = 'block';
        }
    }
    
    toggleSidebar() {
        if (this.isMobile) {
            // 移动端：切换显示/隐藏
            if (this.sidebar.classList.contains('show')) {
                this.hideSidebar();
            } else {
                this.showSidebar();
            }
        } else {
            // 桌面端：切换收缩/展开
            if (this.sidebar.classList.contains('collapsed')) {
                this.expandSidebar();
            } else {
                this.collapseSidebar();
            }
        }
    }
    
    showSidebar() {
        if (this.isMobile) {
            this.sidebar.classList.add('show');
            // 添加遮罩层
            this.addOverlay();
        } else {
            this.sidebar.classList.remove('collapsed');
        }
        this.saveSidebarState();
    }
    
    hideSidebar() {
        if (this.isMobile) {
            this.sidebar.classList.remove('show');
            this.removeOverlay();
        }
        this.saveSidebarState();
    }
    
    collapseSidebar() {
        this.sidebar.classList.add('collapsed');
        this.isCollapsed = true;
        this.saveSidebarState();
    }
    
    expandSidebar() {
        this.sidebar.classList.remove('collapsed');
        this.isCollapsed = false;
        this.saveSidebarState();
    }
    
    addOverlay() {
        if (!document.querySelector('.sidebar-overlay')) {
            const overlay = document.createElement('div');
            overlay.className = 'sidebar-overlay';
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 1040;
            `;
            overlay.addEventListener('click', () => {
                this.hideSidebar();
            });
            document.body.appendChild(overlay);
            
            // 确保侧边栏在遮罩层之上
            if (this.sidebar) {
                this.sidebar.style.zIndex = '1050';
            }
        }
    }
    
    removeOverlay() {
        const overlay = document.querySelector('.sidebar-overlay');
        if (overlay) {
            overlay.remove();
        }
    }
    
    handleResize() {
        const wasMobile = this.isMobile;
        this.isMobile = window.innerWidth <= 768;
        
        if (wasMobile !== this.isMobile) {
            this.setupResponsiveBehavior();
        }
    }
    
    saveSidebarState() {
        if (!this.isMobile) {
            // 只在桌面端保存收缩状态
            localStorage.setItem('admin-sidebar-collapsed', this.isCollapsed);
        }
    }
    
    loadSidebarState() {
        if (!this.isMobile) {
            const savedState = localStorage.getItem('admin-sidebar-collapsed');
            if (savedState === 'true') {
                this.collapseSidebar();
            }
        }
    }
    
    // 工具方法
    static showLoading(button) {
        const originalText = button.innerHTML;
        button.disabled = true;
        button.innerHTML = '<span class="loading-spinner"></span> 处理中...';
        return () => {
            button.disabled = false;
            button.innerHTML = originalText;
        };
    }
    
    static showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        toast.style.cssText = `
            top: 20px;
            right: 20px;
            z-index: 1060;
            min-width: 300px;
        `;
        toast.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(toast);
        
        // 自动移除
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 5000);
    }
    
    static confirmAction(message, callback) {
        if (confirm(message)) {
            callback();
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    window.adminUI = new AdminUI();
    
    // 初始化工具提示
    const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    if (tooltips.length > 0 && typeof bootstrap !== 'undefined') {
        tooltips.forEach(tooltip => {
            new bootstrap.Tooltip(tooltip);
        });
    }
    
    // 处理表单提交
    const forms = document.querySelectorAll('form[data-ajax="true"]');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const button = this.querySelector('button[type="submit"]');
            const resetLoading = AdminUI.showLoading(button);
            
            // 这里可以添加AJAX提交逻辑
            // 暂时使用模拟提交
            setTimeout(() => {
                resetLoading();
                AdminUI.showToast('操作成功完成', 'success');
            }, 1000);
        });
    });
});

// 导出供其他脚本使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AdminUI;
}
